package com.asw.springboot.controller;

import com.asw.springboot.common.CommonController;
import com.asw.springboot.common.exception.ApiException;
import com.asw.springboot.common.result.GlobalErrorInfoEnum;
import com.asw.springboot.common.result.ResultBody;
import com.asw.springboot.po.City;
import com.asw.springboot.service.ICityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping(value = "/city")
public class CityApiController extends CommonController{

    @Autowired
    private ICityService cityService;

    /**
     * 这样写 抛出去的是 ApiException ，CommonController 中对应的可以接受 ApiException 异常的值
     * 但是堆栈里面的异常信息只是定位到了throw 这一行
     * @param token
     * @return
     * @throws ApiException
     */
    @RequestMapping(value = "/error1")
    public ResultBody error1(String token)throws ApiException{
        if (StringUtils.isEmpty(token)){
            return new ResultBody(GlobalErrorInfoEnum.PARAMS_NO_COMPLETE);
        }
        List<City> cityList = cityService.findAllCity();
        try {
            cityList.get(1);
        }catch (Exception e){
            throw new ApiException("");
        }

        return new ResultBody(cityList);
    }


    /***
     * java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 这种抛出去的实际还是 IndexOutOfBoundsException
     * 即使统一异常类中异常处理类型是 ApiException ,那他是捕获不到的
     * @param token
     * @return
     * @throws ApiException
     */
    @RequestMapping(value = "/error2")
    public ResultBody error2(String token)throws ApiException{
        if (StringUtils.isEmpty(token)){
            return new ResultBody(GlobalErrorInfoEnum.PARAMS_NO_COMPLETE);
        }
        List<City> cityList = cityService.findAllCity();
        cityList.get(1);
        return new ResultBody(cityList);
    }


    /***
     *  代码出现异常，程序往上抛，正常全局捕获就好
     *  接口统一返回 {"code":"4000","message":"system error","result":null}
     *  后台出现了什么异常，日志会记录堆栈里面的异常信息
     * @param token
     * @return
     */
    @RequestMapping(value = "/error3")
    public ResultBody error3(String token){
        if (StringUtils.isEmpty(token)){
            return new ResultBody(GlobalErrorInfoEnum.PARAMS_NO_COMPLETE);
        }
        List<City> cityList = cityService.findAllCity();
        cityList.get(1);
        return new ResultBody(cityList);
    }


    @RequestMapping(value = "/error4")
    public ResultBody error4(){
        List<City> cityList = cityService.findAllCity3();
        return new ResultBody(cityList);
    }
}
